﻿using UnityEngine;
using System.Collections;

public class playerControls : MonoBehaviour {
	
	public Animator animator;
	public GameObject bullet;
	public GameObject pyssynpiippu;
	
	void Shoot()
	{
		// luodaan bulletista klooni
		GameObject clone = Instantiate (bullet,
		                                pyssynpiippu.transform.position,
		                                transform.rotation) as GameObject;
		
		// varmistetaan että luoti tuhoutuu joskus
		Destroy (clone, 5f);
		
		// laitetaan vauhtia luotiin
		clone.rigidbody2D.velocity = transform.up * 10;
	}
	
	void FixedUpdate () {
		
		// ammutaan spacella
		if (Input.GetKey (KeyCode.Space))
			Shoot ();
		
		
		// kävelyääni
		if (rigidbody2D.velocity.magnitude > 0.2f) {
			SoundManager.walking = true;
			animator.SetBool ("isWalking", true);
			
			// pyöritys
			Vector3 lookatpos = transform.position;
			lookatpos += new Vector3(rigidbody2D.velocity.x,rigidbody2D.velocity.y,0f);
			LookAtZ (gameObject, lookatpos);
		}
		else
		{
			SoundManager.walking = false;
			animator.SetBool ("isWalking", false);
		}
		
		// ylöspäin liikkuminen
		if (Input.GetKey (KeyCode.W))
			rigidbody2D.AddForce (Vector2.up);
		
		// alas
		if (Input.GetKey (KeyCode.S))
			rigidbody2D.AddForce (-Vector2.up);
		
		// vasen
		if (Input.GetKey (KeyCode.A))
			rigidbody2D.AddForce (-Vector2.right);
		
		// oikee
		if (Input.GetKey (KeyCode.D))
			rigidbody2D.AddForce (Vector2.right);
	}
	
	void LookAtZ(GameObject ob, Vector3 target_pos)
	{
		Vector3 dir = target_pos-ob.transform.position;
		dir.Normalize();
		
		Quaternion target_q = ob.transform.rotation;
		
		if(dir.x > 0f && dir.x > Mathf.Abs(dir.y))// oikeelle
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.down);
		if(dir.x < 0f && dir.x < -Mathf.Abs(dir.y))// vasemmalle
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.up);
		
		if(dir.y > 0f && dir.y > Mathf.Abs(dir.x))// ylös
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.right);
		if(dir.y < 0f && dir.y < -Mathf.Abs(dir.x))// alas
			target_q = Quaternion.LookRotation(target_pos - ob.transform.position,Vector3.left);
		
		target_q.x=0;
		target_q.y=0;
		
		ob.transform.rotation = target_q;
		ob.transform.Rotate (new Vector3 (0, 0, 90));
	}
}

